package hdf5.gui.listeners;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

public abstract class SaveAsListener implements ActionListener{

    protected final JFileChooser fileChooser = new JFileChooser("Save image as ...");
    protected final FileNameExtensionFilter filter = new FileNameExtensionFilter(getExtension(), getExtension());
    protected Component component;

    protected abstract String getExtension();

    protected void setFileChooserProperty(){
        fileChooser.setFileFilter(filter);
        fileChooser.setAcceptAllFileFilterUsed(false);
    }

    public void actionPerformed(ActionEvent e) {
        int returnValue = fileChooser.showSaveDialog(component);
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            file = new File(file.getAbsolutePath() + '.' + getExtension());
            try {
                saveAs(file);
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
    }

    protected abstract void saveAs(File file) throws IOException;
}
